package com.example.windweatherapp;

import static com.example.windweatherapp.constants.Constants.AQI_URL;
import static com.example.windweatherapp.constants.Constants.FORECAST_URL;
import static com.example.windweatherapp.constants.Constants.KEY;
import static com.example.windweatherapp.constants.Constants.NOWWEATHER_URL;
import static com.example.windweatherapp.constants.Constants.PIC_URL;
import static com.example.windweatherapp.constants.Constants.SUGGEST_URL;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.GravityCompat;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.windweatherapp.databinding.ActivityWeatherBinding;
import com.example.windweatherapp.databinding.ForecastItemBinding;
import com.example.windweatherapp.gson.AQI;
import com.example.windweatherapp.gson.BingPic;
import com.example.windweatherapp.gson.Forecast;
import com.example.windweatherapp.gson.NowWeather;
import com.example.windweatherapp.gson.Suggest;
import com.example.windweatherapp.util.HttpUtil;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.google.gson.Gson;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class WeatherActivity extends AppCompatActivity {
    private ActivityWeatherBinding binding;
    private final Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        getWindow().setStatusBarColor(Color.TRANSPARENT);

        binding = ActivityWeatherBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        binding.includeTitle.titleCity.setOnClickListener(v -> 
            binding.drawerLayout.openDrawer(GravityCompat.START)
        );

        Intent intent = getIntent();
        String spot = intent.getStringExtra("spot");
        String location = intent.getStringExtra("location");
        Log.d("test2", "onCreate: " + spot + ":" + location);

        if (spot != null && location != null) {
            showTitle(spot);
            requestWeather(location);
        }
        
        loadBingPic();
    }

    private void loadBingPic() {
        HttpUtil.sendOkHttpRequest(PIC_URL, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                runOnUiThread(() -> {
                    Toast.makeText(WeatherActivity.this, "访问每日一图失败", Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                //step1: 拿到响应数据
                String strJson = response.body().string();
                Log.d("test", "onResponse: "+strJson);
                //step2: 尝试去解析数据
                BingPic bingPic = gson.fromJson(strJson, BingPic.class);
                if(bingPic!=null&& bingPic.getCode()==200){
                    runOnUiThread(() -> {
                        Glide.with(WeatherActivity.this).load(bingPic.getData().getUrl()).into(binding.bingPicImg);
                    });
                }
            }
        });
    }

    private void requestWeather(String location) {
        //abcd  //dcba  RXJava
        String url = String.format(NOWWEATHER_URL, location, KEY);
        Log.d("test", "requestWeather: "+url);
        HttpUtil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

                String strJson = response.body().string();
                Log.d("test", "requestWeather: "+strJson);
                NowWeather nowWeather = gson.fromJson(strJson, NowWeather.class);
                if(nowWeather.getCode().equals("200")){
                    Log.d("test", String.format("当前气温：%s℃，天气情况：%s",nowWeather.getNow().getTemp(),nowWeather.getNow().getText()));
                    showNowWeather(nowWeather);
                }else{
                    Log.d("test", "访问实时天气API出错");
                }
            }
        });


        String url_aqi= String.format(AQI_URL, location, KEY);
        Log.d("test", "request aqi: "+url_aqi);
        HttpUtil.sendOkHttpRequest(url_aqi, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String strJson = response.body().string();
                Log.d("test", "aqi: " + strJson);
                AQI aqi = gson.fromJson(strJson, AQI.class);
                if (aqi.getCode().equals("200")) {
                    Log.d("test", String.format("当前AQI：%s，PM2.5：%s", aqi.getNow().getAqi(), aqi.getNow().getPm2p5()));
                    showAQI(aqi);
                } else {
                    Log.d("test", "访问实时天气API出错");
                }
            }
        });

        String url_suggest= String.format(SUGGEST_URL, location, KEY);
        Log.d("test", "requestWeather: "+url_suggest);
        HttpUtil.sendOkHttpRequest(url_suggest, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String strJson = response.body().string();
                Log.d("test", "suggest: " + strJson);
                Suggest suggest = gson.fromJson(strJson, Suggest.class);
                if (suggest.getCode().equals("200")) {
                    showSuggest(suggest);
                } else {
                    Log.d("test", "访问实时天气API出错");
                }
            }
        });


        String url_forecast = String.format(FORECAST_URL, location, KEY);
        Log.d("test", "request forecast: " + url_forecast);
        HttpUtil.sendOkHttpRequest(url_forecast, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String strJson = response.body().string();
                Log.d("test", "forecast: " + strJson);
                Forecast forecast = gson.fromJson(strJson, Forecast.class);
                if (forecast.getCode().equals("200")) {
                    showForecast(forecast);
                } else {
                    Log.d("test", "访问未来七天的API出错");
                }
            }
        });


    }

    private void showForecast(Forecast forecast) {
        runOnUiThread(() -> {
            binding.includeForecast.forecastLayout.removeAllViews();
            
            // 准备折线图数据
            List<Entry> maxTemps = new ArrayList<>();
            List<Entry> minTemps = new ArrayList<>();
            List<String> dates = new ArrayList<>();
            
            int index = 0;
            for (Forecast.DailyDTO dailyDTO : forecast.getDaily()) {
                ForecastItemBinding binding_item = ForecastItemBinding.inflate(getLayoutInflater());
                binding_item.dateText.setText(dailyDTO.getFxDate());
                binding_item.infoText.setText(dailyDTO.getTextDay());
                binding_item.maxText.setText(dailyDTO.getTempMax());
                binding_item.minText.setText(dailyDTO.getTempMin());
                
                // 添加折线图数据点
                maxTemps.add(new Entry(index, Float.parseFloat(dailyDTO.getTempMax())));
                minTemps.add(new Entry(index, Float.parseFloat(dailyDTO.getTempMin())));
                dates.add(dailyDTO.getFxDate().substring(5)); // 只显示月-日
                
                // 根据天气情况设置对应的图片
                String weatherText = dailyDTO.getTextDay();
                int weatherImageResource;
                if (weatherText.contains("雨")) {
                    weatherImageResource = R.drawable.weather_rain;
                } else if (weatherText.contains("晴")) {
                    weatherImageResource = R.drawable.weather_sunny;
                } else if (weatherText.contains("云") || weatherText.contains("阴")) {
                    weatherImageResource = R.drawable.weather_cloudy;
                } else if (weatherText.contains("雪")) {
                    weatherImageResource = R.drawable.weather_snow;
                } else {
                    weatherImageResource = R.drawable.weather_unknown;
                }
                binding_item.weatherImage.setImageResource(weatherImageResource);
                
                View child = binding_item.getRoot();
                binding.includeForecast.forecastLayout.addView(child);
                index++;
            }
            
            // 设置折线图
            View weatherChartView = binding.includeWeatherChart.getRoot();
            LineChart temperatureChart = weatherChartView.findViewById(R.id.temperature_chart);
            setupTemperatureChart(temperatureChart, maxTemps, minTemps, dates);
        });
    }
    
    private void setupTemperatureChart(LineChart chart, 
                                     List<Entry> maxTemps, 
                                     List<Entry> minTemps, 
                                     List<String> dates) {
        try {
            // 创建最高温度数据集
            LineDataSet maxTempDataSet = new LineDataSet(maxTemps, "最高温度");
            maxTempDataSet.setColor(Color.RED);
            maxTempDataSet.setCircleColor(Color.RED);
            maxTempDataSet.setLineWidth(2f);
            maxTempDataSet.setCircleRadius(4f);
            maxTempDataSet.setDrawValues(true);
            maxTempDataSet.setValueTextColor(Color.WHITE);
            maxTempDataSet.setMode(LineDataSet.Mode.LINEAR);
            
            // 创建最低温度数据集
            LineDataSet minTempDataSet = new LineDataSet(minTemps, "最低温度");
            minTempDataSet.setColor(Color.BLUE);
            minTempDataSet.setCircleColor(Color.BLUE);
            minTempDataSet.setLineWidth(2f);
            minTempDataSet.setCircleRadius(4f);
            minTempDataSet.setDrawValues(true);
            minTempDataSet.setValueTextColor(Color.WHITE);
            minTempDataSet.setMode(LineDataSet.Mode.LINEAR);
            
            // 创建折线图数据对象
            ArrayList<ILineDataSet> dataSets = new ArrayList<>();
            dataSets.add(maxTempDataSet);
            dataSets.add(minTempDataSet);
            LineData lineData = new LineData(dataSets);
            
            // 配置X轴
            XAxis xAxis = chart.getXAxis();
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
            xAxis.setTextColor(Color.WHITE);
            xAxis.setDrawGridLines(false);
            xAxis.setGranularity(1f);
            xAxis.setValueFormatter(new IndexAxisValueFormatter(dates));
            
            // 配置Y轴
            YAxis leftAxis = chart.getAxisLeft();
            leftAxis.setTextColor(Color.WHITE);
            leftAxis.setDrawGridLines(true);
            leftAxis.setGridColor(Color.argb(77, 255, 255, 255)); // 设置网格线颜色，透明度为 0.3
            
            YAxis rightAxis = chart.getAxisRight();
            rightAxis.setEnabled(false);
            
            // 其他图表设置
            chart.setData(lineData);
            Description description = new Description();
            description.setEnabled(false);
            chart.setDescription(description);
            
            Legend legend = chart.getLegend();
            legend.setTextColor(Color.WHITE);
            
            chart.setTouchEnabled(true);
            chart.setDragEnabled(true);
            chart.setScaleEnabled(false);
            
            // 刷新图表
            chart.invalidate();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("WeatherActivity", "Error setting up temperature chart: " + e.getMessage());
        }
    }

    private void showSuggest(Suggest suggest) {
        runOnUiThread(() -> {
            binding.includeSuggestion.wearText.setText(suggest.getDaily().get(0).getText());
            binding.includeSuggestion.sportText.setText(suggest.getDaily().get(1).getText());
            binding.includeSuggestion.comfortText.setText(suggest.getDaily().get(2).getText());
        });
    }
    private void showAQI(AQI aqi) {
        runOnUiThread(() -> {
            binding.includeAqi.aqiText.setText(aqi.getNow().getAqi());
            binding.includeAqi.pm25Text.setText(aqi.getNow().getPm2p5());
        });
    }


    private void showNowWeather(NowWeather nowWeather) {
        runOnUiThread(() -> {
            binding.includeNow.degreeText.setText(nowWeather.getNow().getTemp() + "℃");
            binding.includeNow.weatherInfoText.setText(nowWeather.getNow().getText());
            
            // 根据天气情况设置不同的图片
            String weatherText = nowWeather.getNow().getText();
            int weatherImageResource;
            if (weatherText.contains("雨")) {
                weatherImageResource = R.drawable.weather_rain;  // 雨天
            } else if (weatherText.contains("晴")) {
                weatherImageResource = R.drawable.weather_sunny;  // 晴天
            } else if (weatherText.contains("云") || weatherText.contains("阴")) {
                weatherImageResource = R.drawable.weather_cloudy;  // 多云/阴天
            } else {
                weatherImageResource = R.drawable.weather_other;  // 其他天气
            }
            binding.includeNow.weatherImage.setImageResource(weatherImageResource);
        });
    }

    private void showTitle(String spot) {
        binding.includeTitle.titleCity.setText(spot);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        binding.includeTitle.titleUpdateTime.setText(format.format(new Date()));
    }
}